package com.an.pay.aspect.ali.pc;

import com.alipay.api.AlipayConstants;
import com.alipay.api.internal.util.AlipaySignature;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.util.Map;

@Aspect
@Slf4j
@Component
public class AliPayNotifyAspect {

    @Autowired
    private Environment config;

    @Pointcut(value = "@annotation(com.an.pay.annotation.AliPayNotify)")
    public void point(){}

    @Around(value = "point()")
    public String around(ProceedingJoinPoint joinPoint) {

        try {
            Map<String,String> params = (Map)joinPoint.getArgs()[0];

            //异步通知验签
            boolean signVerified = AlipaySignature.rsaCheckV1(
                    params,
                    config.getProperty("alipay.alipay-public-key"),
                    AlipayConstants.CHARSET_UTF8,
                    AlipayConstants.SIGN_TYPE_RSA2); //调用SDK验证签名

            if(!signVerified){
                //验签失败则记录异常日志，并在response中返回failure.
                log.error("支付成功异步通知验签失败！");
                return "fail";
            }
            String outTradeNo = params.get("out_trade_no");
            String proceed = (String) joinPoint.proceed(new Object[]{params,outTradeNo});
            return proceed;
        } catch (Throwable e) {
            e.printStackTrace();
            return "fail";
        }
    }
}
